<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>时间平台跳跃</title>
    <style>
        /* 基础样式 */
        body {
            margin: 0;
            overflow: hidden;
            font-family: Arial, sans-serif;
            background-color: #222;
            color: white;
        }
        
        /* 游戏容器 */
        #game-container {
            position: relative;
            width: 800px;
            height: 600px;
            margin: 20px auto;
            background-color: #333;
            overflow: hidden;
        }
        
        /* 关卡选择界面 */
        #level-select {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.8);
            display: flex;
            flex-direction: column;
            justify-content: flex-start;
            align-items: center;
            z-index: 100;
            padding-top: 20px;
        }
        
        /* 关卡按钮容器 */
        #level-buttons-container {
            display: grid;
            grid-template-columns: repeat(6, 1fr);
            gap: 10px;
            max-height: 80%;
            overflow-y: auto;
            padding: 20px;
            width: 90%;
        }
        
        /* 关卡按钮样式 */
        .level-btn {
            margin: 5px;
            padding: 10px 15px;
            font-size: 16px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .level-btn:hover:not(:disabled) {
            background-color: #45a049;
            transform: scale(1.05);
        }
        
        .level-btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        
        /* 玩家角色样式 */
        #player {
            position: absolute;
            width: 40px;
            height: 60px;
            background-color: #3498db;
            border-radius: 10px;
            bottom: 50px;
            left: 50px;
            transition: transform 0.2s;
            z-index: 2;
        }
        
        /* 玩家眼睛样式 */
        #player .eye {
            position: absolute;
            top: 15px;
            width: 8px;
            height: 8px;
            background-color: white;
            border-radius: 50%;
        }
        
        #player .eye-left {
            left: 30px;
        }
        
        #player .eye-right {
            left: 20px;
        }
        
        /* 玩家时间显示 */
        #player-time {
            position: absolute;
            width: auto;
            min-width: 80px;
            text-align: center;
            font-size: 28px;
            color: #fff;
            text-shadow: 
                2px 2px 4px rgba(0, 0, 0, 0.8),
                0 0 15px rgba(255, 255, 255, 0.5);
            font-weight: bold;
            pointer-events: none;
            z-index: 3;
            font-family: 'Arial Rounded MT Bold', 'Segoe UI', sans-serif;
            font-variant-numeric: tabular-nums;
            letter-spacing: 1px;
            -webkit-font-smoothing: antialiased;
            -moz-osx-font-smoothing: grayscale;
            text-rendering: optimizeLegibility;
            transition: transform 0.2s ease;
            z-index:10;
        }
        
        /* 玩家朝向 */
        #player.left {
            transform: scaleX(-1);
        }
        
        /* 平台和墙壁基础样式 */
        .platform, .wall {
            position: absolute;
            background-color: #2ecc71;
            opacity: 0.3;
            z-index:5
        }
        
        .platform {
            height: 30px;
        }
        
        .wall {
            width: 30px;
        }
        
        /* 激活的平台和墙壁 */
        .platform.active, .wall.active {
            opacity: 1;
        }
        
        /* 平台和墙壁上的时间标签 */
        .platform::after, .wall::after {
            content: attr(data-time);
            position: absolute;
            bottom: 5px;
            left: 0;
            width: 100%;
            text-align: center;
            color: white;
            font-size: 1.2em;
        }
        
        /* 终点门样式 */
        #door {
            position: absolute;
            width: 60px;
            height: 100px;
            background: linear-gradient(to bottom, #3498db, #2980b9);
            border: 2px solid #ffffff;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(255, 255, 255, 0.5);
            bottom: 0;
            z-index: 1;
        }
        
        #door::after {
            content: "终点";
            position: absolute;
            top: 15px;
            left: 0;
            width: 100%;
            text-align: center;
            color: white;
            font-size: 18px;
            font-weight: bold;
        }
        
        /* 锁住的门样式 */
        #door.locked {
            background: linear-gradient(to bottom, #e74c3c, #c0392b);
            box-shadow: 0 0 10px rgba(231, 76, 60, 0.5);
        }
        
        #door.locked::after {
            content: "locked";
        }
        
        /* 播放按钮样式 */
        .play-button {
            position: absolute;
            width: 30px;
            height: 30px;
            background-color: #f1c40f;
            clip-path: polygon(0 0, 100% 50%, 0 100%);
        }
        
/* 钥匙样式 */
.key {
    position: absolute;
    width: 5px; /* 细矩形的宽度 */
    height: 50px; /* 细矩形的长度 */
    background: #FFD700; /* 钥匙主体颜色 */
    margin: 50px auto; /* 居中显示 */
    border-radius: 2px; /* 细矩形的圆角 */
}

.key::before {
    content: '';
    position: absolute;
    top: -5px; /* 空心圆与细矩形的间隔 */
    left: 50%;
    transform: translateX(-50%);
    width: 10px; /* 空心圆的直径 */
    height: 10px;
    background: #FFF; /* 空心圆的颜色 */
    border: 5px solid #FFD700; /* 空心圆边框颜色 */
    border-radius: 40%; /* 空心圆 */
}


.key::after {
    content: '';
    position: absolute;
    bottom: 3px; /* 小正方形与细矩形的间隔 */
    left: 50%;
    transform: translateX(-50%) translateX(2px); /* 向右偏移2px */
    width: 6px; /* 小正方形的边长 */
    height: 6px;
    background: #FFD700; /* 小正方形颜色 */
    border: 1px solid #FFF; /* 小正方形边框颜色 */
}


/* 钥匙摆动动画 */
@keyframes swing {
    0%, 100% {
        transform: rotate(-5deg);
    }
    50% {
        transform: rotate(5deg);
    }
}
/* 应用动画 */
.key {
    animation: swing 2s ease-in-out infinite;
}



        /* 控制提示 */
        #controls {
            position: absolute;
            bottom: 10px;
            left: 10px;
            color: #aaa;
            font-size: 14px;
        }
        
        /* 钥匙计数显示 */
        #keys-collected {
            position: absolute;
            top: 10px;
            right: 10px;
            color: #f1c40f;
            font-size: 20px;
            font-weight: bold;
            z-index: 50;
        }
        
        /* 退出按钮 */
        #exit-btn {
            position: absolute;
            top: 10px;
            left: 10px;
            padding: 5px 10px;
            background-color: #e74c3c;
            color: white;
            border: none;
            border-radius: 3px;
            cursor: pointer;
            z-index: 50;
        }
        
        #exit-btn:hover {
            background-color: #c0392b;
        }
        
        /* 退出菜单 */
        #exit-menu {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: rgba(0, 0, 0, 0.9);
            padding: 20px;
            border-radius: 5px;
            display: none;
            flex-direction: column;
            z-index: 200;
        }
        
        .exit-option {
            margin: 10px;
            padding: 10px 20px;
            background-color: #3498db;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }
        
        .exit-option:hover {
            background-color: #2980b9;
        }
        
        /* 胜利效果 */
        #victory-effect {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: radial-gradient(circle, rgba(255,255,255,0.8) 0%, rgba(255,255,255,0) 70%);
            opacity: 0;
            pointer-events: none;
            z-index: 10;
            transition: opacity 1s;
        }
        
        /* 胜利文字 */
        #victory-text {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            font-size: 60px;
            font-weight: bold;
            color: #f1c40f;
            text-shadow: 0 0 10px rgba(0, 0, 0, 0.8);
            opacity: 0;
            z-index: 11;
            transition: all 1s;
        }
        
        /* 游戏结束文字 */
        #game-over {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            font-size: 60px;
            font-weight: bold;
            color: #e74c3c;
            text-shadow: 0 0 10px rgba(0, 0, 0, 0.8);
            opacity: 0;
            z-index: 11;
            transition: all 1s;
        }
        
        /* 新增告示板样式 */
        .sign {
            position: absolute;
            background-color: #333;
            border-radius: 10px;
            padding: 10px;
            text-align: center;
            display: flex;
            justify-content: center;
            align-items: center;
            pointer-events: none;
            z-index: 0;
            font-size: 20px;
            line-height: 1.4;
            word-break: break-word;
        }

 /* 美化沙漏样式 */
.hourglass {
    position: absolute;
    width: 40px;
    height: 60px;
    z-index: 9;
    animation: float 3s ease-in-out infinite;
}

.hourglass-body {
    position: absolute;
    width: 100%;
    height: 100%;
    background: linear-gradient(135deg, #007BFF 0%, #004C99 100%);
    border-radius: 8px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1), 
                0 8px 16px rgba(0, 0, 0, 0.1),
                inset 0 -4px 8px rgba(255, 255, 255, 0.2),
                inset 0 4px 8px rgba(0, 0, 0, 0.1);
    border: 2px solid rgba(255, 255, 255, 0.8);
}

.hourglass::before {
    content: "";
    position: absolute;
    top: 8px;
    left: 50%;
    transform: translateX(-50%);
    width: 30px;
    height: 20px;
    background: linear-gradient(to bottom, rgba(255, 255, 255, 0.9) 0%, rgba(240, 240, 255, 0.8) 100%);
    clip-path: polygon(50% 100%, 0% 0%, 100% 0%);
    border-radius: 3px 3px 0 0;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    z-index: 10;
}

.hourglass::after {
    content: "";
    position: absolute;
    bottom: 8px;
    left: 50%;
    transform: translateX(-50%);
    width: 30px;
    height: 20px;
    background: linear-gradient(to bottom, rgba(240, 240, 255, 0.8) 0%, rgba(255, 255, 255, 0.9) 100%);
    clip-path: polygon(50% 0%, 0% 100%, 100% 100%);
    border-radius: 0 0 3px 3px;
    box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);
    z-index: 10;
}

.sand {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    width: 12px;
    background: linear-gradient(to bottom, #FF4500 0%, #FF6347 100%);
    z-index: 11;
    animation: sand-flow 3s linear infinite;
}

.sand-top {
    top: 10px;
    height: 18px;
    clip-path: polygon(50% 100%, 0% 0%, 100% 0%);
}

.sand-bottom {
    bottom: 10px;
    height: 0;
    clip-path: polygon(50% 0%, 0% 100%, 100% 100%);
    animation: sand-accumulate 3s linear infinite;
}

.sand-stream {
    top: 28px;
    height: 4px;
    width: 2px;
    background: #FF4500;
    animation: sand-stream 0.5s linear infinite;
}

.hourglass.cooldown {
    filter: grayscale(50%) brightness(0.8);
    animation: none;
}

@keyframes float {
    0%, 100% { transform: translateY(0); }
    50% { transform: translateY(-8px); }
}

@keyframes sand-flow {
    0% { opacity: 1; }
    80% { opacity: 1; }
    100% { opacity: 0; }
}

@keyframes sand-accumulate {
    0% { height: 0; }
    80% { height: 18px; }
    100% { height: 18px; }
}

@keyframes sand-stream {
    0% { height: 0; transform: translate(-50%, 0); }
    50% { height: 4px; transform: translate(-50%, -2px); }
    100% { height: 0; transform: translate(-50%, -4px); }
}

</style>
</head>
<body>
    <div id="game-container">
        <button id="exit-btn">退出</button>
        <div id="exit-menu">
            <h2 style="text-align: center; margin-top: 0;">退出菜单</h2>
            <button class="exit-option" id="restart-btn">重新开始本关</button>
            <button class="exit-option" id="level-select-btn">返回选关界面</button>
        </div>
        
        <div id="level-select">
            <h1>选择关卡</h1>
            <div id="level-buttons-container"></div>
        </div>
        
        <div id="player">
            <div class="eye eye-left"></div>
            <div class="eye eye-right"></div>
        </div>
        <div id="player-time">10.00</div>
        <div id="keys-collected">钥匙: 0/0</div>
        
        <div id="victory-effect"></div>
        <div id="victory-text">通关成功！</div>
        <div id="game-over">时间耗尽！</div>
        
    </div>

    <!-- 引入关卡数据 -->
    <script src="levels.js"></script>        

    <script>
        // 游戏变量
        const gameContainer = document.getElementById('game-container');
        const player = document.getElementById('player');
        const playerTime = document.getElementById('player-time');
        const levelSelect = document.getElementById('level-select');
        const exitBtn = document.getElementById('exit-btn');
        const exitMenu = document.getElementById('exit-menu');
        const restartBtn = document.getElementById('restart-btn');
        const levelSelectBtn = document.getElementById('level-select-btn');
        const victoryEffect = document.getElementById('victory-effect');
        const victoryText = document.getElementById('victory-text');
        const gameOverText = document.getElementById('game-over');
        const levelButtonsContainer = document.getElementById('level-buttons-container');
        const keysCollectedDisplay = document.getElementById('keys-collected');
        
        // 游戏物理参数
        let gameWidth = 24000;
        let gameHeight = 12000;
        let playerX = 50;
        let playerY = 50;
        let playerWidth = 40;
        let playerHeight = 60;
        let playerVelX = 0;
        let playerVelY = 0;
        let isJumping = false;
        let canDoubleJump = false;
        let currentTime = 10.00;
        let timeRunning = false;
        let gameRunning = false;
        let platforms = [];
        let walls = [];
        let keys = []; // 钥匙数组
        let hourglasses = []; // 沙漏数组
        let collectedKeys = 0; // 已收集的钥匙数量
        let totalKeys = 0; // 总钥匙数量
        let door = null;
        let playButton = null;
        let currentLevel = 1;
        let gameLoop;
        let isOnPlatform = false;
        let timeDirection = -1; // 1表示时间正向流动，-1表示反向流动
        let hourglassCooldown = 0; // 沙漏冷却计时器
// 音频变量
let audioContext;
let tickGain;
let lastSecond = 10; // 用于跟踪上一秒
let tickTock = false; // 用于交替播放高音和低音
        
        // 物理常数
        const gravity = 0.6;
        const moveSpeed = 4.9;
        const jumpForce = 13;
        
        // 镜头控制变量
        let cameraX = 0;
        let cameraY = 0;
        const cameraSpeed = 2;
        const cameraMargin = 300;
        const screenWidth = gameContainer.offsetWidth;
        const screenHeight = gameContainer.offsetHeight;
        
        // 键盘状态
        const keyStates = {
            a: false,
            d: false,
            k: false,
            s: false
        };
        
        /**
         * 初始化游戏关卡
         * @param {number} level - 要加载的关卡编号
         */
        function initGame(level) {
            // 清除现有游戏元素
            document.querySelectorAll('.platform').forEach(p => p.remove());
            document.querySelectorAll('.wall').forEach(w => w.remove());
            document.querySelectorAll('.sign').forEach(s => s.remove());
            document.querySelectorAll('.key').forEach(k => k.remove());
            document.querySelectorAll('.hourglass').forEach(h => h.remove());
            if (door) door.remove();
            if (playButton) playButton.remove();
            
    // 初始化音频上下文
    if (!audioContext) {
        audioContext = new (window.AudioContext || window.webkitAudioContext)();
        tickGain = audioContext.createGain();
        tickGain.gain.value = 0.1; // 设置音量
        tickGain.connect(audioContext.destination);
    }
    
    // 重置音频状态
    lastSecond = 10;
    tickTock = false;

            // 重置游戏状态
            victoryEffect.style.opacity = 0;
            victoryText.style.opacity = 0;
            victoryText.style.transform = 'translate(-50%, -50%) scale(0.5)';
            gameOverText.style.opacity = 0;
            gameOverText.style.transform = 'translate(-50%, -50%) scale(0.5)';
            
            platforms = [];
            walls = [];
            keys = [];
            hourglasses = [];
            collectedKeys = 0;
            timeRunning = false;
            isOnPlatform = false;
            timeDirection = -1;
            hourglassCooldown = 0;
            
            // 重置玩家状态
            const startPos = levels[level].playerStart || { x: 50, y: 50 }; // 获取玩家初始位置
            playerX = startPos.x;
            playerY = startPos.y;
            playerVelX = 0;
            playerVelY = 0;
            isJumping = false;
            canDoubleJump = false;

            player.style.left = playerX + 'px';
            player.style.bottom = playerY + 'px';
            player.classList.remove('left');
            updatePlayerTimePosition();
            
            // 重置计时器
            currentTime = 10.00;
            updateTimer();
            
            // 创建告示板
            if (levels[level].signs) {
                levels[level].signs.forEach(sign => {
                    const signElement = document.createElement('div');
                    signElement.className = 'sign';
                    signElement.style.left = sign.x + 'px';
                    signElement.style.bottom = sign.y + 'px';
                    signElement.style.width = sign.width + 'px';
                    signElement.style.height = sign.height + 'px';
                    signElement.style.fontSize = (sign.fontSize || 20) + 'px';
                    signElement.style.color = sign.color || '#ffffff';
                    signElement.textContent = sign.text;
                    gameContainer.appendChild(signElement);
                });
            }

            // 创建平台
            levels[level].platforms.forEach((plat, index) => {
                const platform = document.createElement('div');
                platform.className = 'platform';
                platform.style.left = plat.x + 'px';
                platform.style.bottom = plat.y + 'px';
                platform.style.width = plat.width + 'px';
                platform.dataset.time = plat.time;
                gameContainer.appendChild(platform);
                
                platforms.push({
                    element: platform,
                    x: plat.x,
                    y: plat.y,
                    width: plat.width,
                    time: plat.time
                });
            });
            
            // 创建墙壁
            levels[level].walls.forEach((wall, index) => {
                const wallElement = document.createElement('div');
                wallElement.className = 'wall';
                wallElement.style.left = wall.x + 'px';
                wallElement.style.bottom = wall.y + 'px';
                wallElement.style.height = wall.height + 'px';
                wallElement.dataset.time = wall.time;
                gameContainer.appendChild(wallElement);
                
                walls.push({
                    element: wallElement,
                    x: wall.x,
                    y: wall.y,
                    height: wall.height,
                    time: wall.time
                });
            });
            
            // 创建钥匙
            if (levels[level].keys) {
                totalKeys = levels[level].keys.length;
                levels[level].keys.forEach((key, index) => {
                    const keyElement = document.createElement('div');
                    keyElement.className = 'key';
                    keyElement.style.left = key.x + 'px';
                    keyElement.style.bottom = key.y + 'px';
                    gameContainer.appendChild(keyElement);
                    
                    keys.push({
                        element: keyElement,
                        x: key.x,
                        y: key.y,
                        collected: false
                    });
                });
                updateKeysDisplay();
            } else {
                totalKeys = 0;
                updateKeysDisplay();
            }

            // 创建沙漏
            if (levels[level].hourglasses) {
                levels[level].hourglasses.forEach((hourglass, index) => {
                    const hourglassElement = document.createElement('div');
                    hourglassElement.className = 'hourglass';
                    hourglassElement.style.left = hourglass.x + 'px';
                    hourglassElement.style.bottom = hourglass.y + 'px';
                    gameContainer.appendChild(hourglassElement);
                    
                    hourglasses.push({
                        element: hourglassElement,
                        x: hourglass.x,
                        y: hourglass.y,
                        collected: false,
                        cooldown: 0
                    });
                });
            }
         
            // 创建终点门
            door = document.createElement('div');
            door.id = 'door';
            door.style.left = levels[level].door.x + 'px';
            door.style.bottom = levels[level].door.y + 'px';
            
            // 如果有钥匙且未收集完，门是锁住的
            if (totalKeys > 0) {
                door.classList.add('locked');
            }
            
            gameContainer.appendChild(door);
            
            // 创建播放按钮道具
            playButton = document.createElement('div');
            playButton.className = 'play-button';
            playButton.style.left = levels[level].playButton.x + 'px';
            playButton.style.bottom = levels[level].playButton.y + 'px';
            gameContainer.appendChild(playButton);
            
            // 开始游戏循环
            if (gameLoop) clearInterval(gameLoop);
            gameRunning = true;
            gameLoop = setInterval(updateGame, 20);
        }
        
        /**
         * 更新钥匙显示
         */
        function updateKeysDisplay() {
            keysCollectedDisplay.textContent = `钥匙: ${collectedKeys}/${totalKeys}`;
        }
        
        /**
         * 检查钥匙收集
         */
        function checkKeyCollection() {
            keys.forEach(key => {
                if (!key.collected) {
                    const keyLeft = key.x;
                    const keyRight = key.x + 20;
                    const keyBottom = key.y;
                    const keyTop = key.y + 40;
                    
                    if (playerX + playerWidth > keyLeft &&
                        playerX < keyRight &&
                        playerY + playerHeight > keyBottom &&
                        playerY < keyTop) {
                        
                        key.collected = true;
                        collectedKeys++;
                        key.element.remove();
                        updateKeysDisplay();
                        
                        // 检查是否收集了所有钥匙
                        if (collectedKeys === totalKeys) {
                            door.classList.remove('locked');
                        }
                    }
                }
            });
        }

        /**
         * 检查沙漏收集
         */
        function checkHourglassCollection() {
            hourglasses.forEach(hourglass => {
                if (!hourglass.collected && hourglass.cooldown <= 0) {
                    const hourglassLeft = hourglass.x;
                    const hourglassRight = hourglass.x + 30;
                    const hourglassBottom = hourglass.y;
                    const hourglassTop = hourglass.y + 40;
                    
                    if (playerX + playerWidth > hourglassLeft &&
                        playerX < hourglassRight &&
                        playerY + playerHeight > hourglassBottom &&
                        playerY < hourglassTop) {
                        
                        // 反转时间流向
                        timeDirection *= -1;
                        
                        // 设置沙漏冷却时间
                        hourglass.cooldown = 50; // 50帧，约1秒
                        hourglass.element.classList.add('cooldown');
                    }
                }
            });
        }

        /**
         * 更新沙漏冷却状态
         */
        function updateHourglassCooldowns() {
            hourglassCooldown--;
            if (hourglassCooldown < 0) hourglassCooldown = 0;

            hourglasses.forEach(hourglass => {
                if (hourglass.cooldown > 0) {
                    hourglass.cooldown--;
                    if (hourglass.cooldown <= 0) {
                        hourglass.element.classList.remove('cooldown');
                    }
                }
            });
        }
        
        /**
         * 更新游戏状态
         */
        function updateGame() {
            // 更新时间
            if (timeRunning) {
                currentTime += 0.02 * timeDirection; // 根据时间方向增减时间
                
                // 检查时间边界
                if (currentTime <= 0) {
                    currentTime = 0;
                    timeRunning = false;
                } else if (currentTime >= 100) {
                    currentTime = 100;
                }
                
                updateTimer();
       		// 播放滴答声
        	const currentSecond = Math.floor(currentTime);
        	if (currentSecond !== lastSecond) {
            		playTickSound();
            		lastSecond = currentSecond;
        	}
		else if ( Math.round(Math.abs(currentTime - currentSecond) *1000) % 100 == 0){
			const k= Math.round(Math.abs(currentTime-lastSecond)  /  0.1);
			if (k == 0 || k == 10){ }
			else if ( k % 2 == 0 && currentTime < 3)  playTickSound();
			else if ( k%5 == 0 && currentTime < 7 && currentTime>3)  playTickSound();	
		}

            }
            
            // 检查游戏是否结束
            if (currentTime <= 0.01 && timeRunning) {
                clearInterval(gameLoop);
                gameRunning = false;
                showGameOver();
                return;
            }
            
            // 处理玩家移动
            playerVelX = 0;
            if (keyStates.a) {
                playerVelX = -moveSpeed;
                player.classList.add('left');
            } else if (keyStates.d) {
                playerVelX = moveSpeed;
                player.classList.remove('left');
            }
            
            // 处理重力
            if (isJumping) {
                playerVelY -= gravity;
		if (playerVelY < -20) playerVelY = -20;
            } else {
                playerVelY = 0;
            }
            
            // 更新玩家位置
            playerX += playerVelX;
            playerY += playerVelY;
            
            // 边界检查
            if (playerX < 0) playerX = 0;
            if (playerX > gameWidth - playerWidth) playerX = gameWidth - playerWidth;
            
            if (playerY > gameHeight - playerHeight) {
                playerY = gameHeight - playerHeight;
                playerVelY = 0;
            }
            
            if (playerY < 0) {
                playerY = 0;
                playerVelY = 0;
                isJumping = false;
                canDoubleJump = true;
            }
            
            // 更新镜头位置
            if (playerX < cameraX + cameraMargin) {
                cameraX = playerX - cameraMargin;
            } else if (playerX > cameraX + screenWidth - cameraMargin) {
                cameraX = playerX - (screenWidth - cameraMargin);
            }
            if (playerY < cameraY + cameraMargin) {
                cameraY = playerY - cameraMargin;
            } else if (playerY > cameraY + screenHeight - cameraMargin) {
                cameraY = playerY - (screenHeight - cameraMargin);
            }
            
            cameraX = Math.max(0, Math.min(gameWidth - screenWidth, cameraX));
            cameraY = Math.max(0, Math.min(gameHeight - screenHeight, cameraY));
            
            // 更新玩家显示位置
            player.style.left = (playerX - cameraX) + 'px';
            player.style.bottom = (playerY - cameraY) + 'px';
            updatePlayerTimePosition();
            
            // 更新平台和墙壁位置
            platforms.forEach(platform => {
                platform.element.style.left = (platform.x - cameraX) + 'px';
                platform.element.style.bottom = (platform.y - cameraY) + 'px';
            });
            
            walls.forEach(wall => {
                wall.element.style.left = (wall.x - cameraX) + 'px';
                wall.element.style.bottom = (wall.y - cameraY) + 'px';
            });
            
            // 更新钥匙位置
            keys.forEach(key => {
                if (!key.collected) {
                    key.element.style.left = (key.x - cameraX) + 'px';
                    key.element.style.bottom = (key.y - cameraY) + 'px';
                }
            });

            // 更新沙漏位置
            hourglasses.forEach(hourglass => {
                hourglass.element.style.left = (hourglass.x - cameraX) + 'px';
                hourglass.element.style.bottom = (hourglass.y - cameraY) + 'px';
            });
            
            // 更新门位置
            door.style.left = (levels[currentLevel].door.x - cameraX) + 'px';
            door.style.bottom = (levels[currentLevel].door.y - cameraY) + 'px';
            
            // 更新播放按钮位置
            if (playButton) {
                playButton.style.left = (levels[currentLevel].playButton.x - cameraX) + 'px';
                playButton.style.bottom = (levels[currentLevel].playButton.y - cameraY) + 'px';
            }
            
            // 更新告示板位置
            if (levels[currentLevel].signs) {
                document.querySelectorAll('.sign').forEach((sign, index) => {
                    const signData = levels[currentLevel].signs[index];
                    sign.style.left = (signData.x - cameraX) + 'px';
                    sign.style.bottom = (signData.y - cameraY) + 'px';
                });
            }
            
            // 检查钥匙收集
            checkKeyCollection();

            // 检查沙漏收集
            checkHourglassCollection();

            // 更新沙漏冷却状态
            updateHourglassCooldowns();
            
            // 检查平台碰撞
            const currentSecond = Math.floor(currentTime);
            let standingOnPlatform = false;
            
            platforms.forEach(platform => {
                let isActive = false;
                const timeCondition = platform.time;
                
                // 根据时间条件判断平台是否激活
                if (timeCondition.endsWith("*")) {
                    const x = parseInt(timeCondition.slice(0, -1));
                    isActive = currentSecond !== x;
		    if (currentTime+0.15>currentSecond+1 && !isActive)  isActive = (currentSecond+1) !== x;
                } else if (timeCondition.endsWith("n")) {
                    const k = parseInt(timeCondition.slice(0, -1));
                    isActive = currentSecond % k === 0;
		    if (currentTime+0.15>currentSecond+1 && !isActive)  isActive = (currentSecond+1) % k === 0;
                } else if (timeCondition.startsWith("<=")) {
                    const x = parseInt(timeCondition.slice(2));
                    isActive = currentSecond <= x;
                } else if (timeCondition.startsWith(">=")) {
                    const x = parseInt(timeCondition.slice(2));
                    isActive = currentSecond >= x;
                } else {
                    isActive = currentSecond === parseInt(timeCondition);
                    if (currentTime+0.15>currentSecond+1 && !isActive)   isActive = (currentSecond+1) === parseInt(timeCondition);
                }
                
                platform.element.classList.toggle('active', isActive);
                
                // 处理平台碰撞
                if (isActive && !keyStates.s) {
                    if (playerX + playerWidth-10 > platform.x &&
                        playerX < platform.x + platform.width-10 &&
                        playerY <= platform.y + 30 &&
                        playerY >= platform.y + 10 &&
                        playerVelY <= 0) {
                        
                        playerY = platform.y + 30;
                        playerVelY = 0;
                        isJumping = false;
                        canDoubleJump = true;
                        standingOnPlatform = true;
                    }
                }
            });
            
            // 更新跳跃状态
            if (isOnPlatform && !standingOnPlatform) {
                isJumping = true;
            }
            isOnPlatform = standingOnPlatform;
            

            let standingOnWall = false;

            walls.forEach(wall => {
                let isActive = false;
                const timeCondition = wall.time;

                // 根据时间条件判断墙壁是否激活
                if (timeCondition.endsWith("*")) {
                    const x = parseInt(timeCondition.slice(0, -1));
                    isActive = currentSecond !== x;
                } else if (timeCondition.endsWith("n")) {
                    const k = parseInt(timeCondition.slice(0, -1));
                    isActive = currentSecond % k === 0;
                } else if (timeCondition.startsWith("<=")) {
                    const x = parseInt(timeCondition.slice(2));
                    isActive = currentSecond <= x;
                } else if (timeCondition.startsWith(">=")) {
                    const x = parseInt(timeCondition.slice(2));
                    isActive = currentSecond >= x;
                } else {
                    isActive = currentSecond === parseInt(timeCondition);
                }

                wall.element.classList.toggle('active', isActive);

                // 处理墙壁碰撞
                if (isActive) {
                    // 检查是否与墙壁碰撞
                    if (playerX + playerWidth > wall.x &&
                        playerX < wall.x + 30 &&
                        playerY + playerHeight > wall.y &&
                        playerY < wall.y + wall.height) {
                        
                        // 计算碰撞方向
                        const playerBottom = playerY + playerHeight;
                        const wallTop = wall.y + wall.height;
                        
                        // 从顶部碰撞（玩家底部接近墙壁顶部，且下落中）
                        if (playerY >= wallTop-20  && playerVelY <= 0) {
                            playerY = wallTop;
                            playerVelY = 0;
                            isJumping = false;
                            canDoubleJump = true;
                            standingOnWall = true;
                        } 
                        // 从侧面碰撞
                        else {
                            // 根据玩家速度方向决定击退方向
                            if (playerVelX > 0) {
                                playerX = wall.x - playerWidth;
                            } else if (playerVelX < 0) {
                                playerX = wall.x + 30;
                            }
                            // 如果速度很小，则根据玩家中心位置决定
                            else if (playerX + playerWidth / 2 < wall.x + 15) {
                                playerX = wall.x - playerWidth;
                            } else {
                                playerX = wall.x + 30;
                            }
                        }
                    }
                }
            });

            // 保持原有的站立状态检测逻辑
            if (!standingOnPlatform && !standingOnWall && isOnPlatform) {
                isJumping = true;
            }
            isOnPlatform = standingOnPlatform || standingOnWall;
            
            // 检查是否到达终点
            const doorCenterX = levels[currentLevel].door.x + door.offsetWidth / 2;
            const doorCenterY = levels[currentLevel].door.y + door.offsetHeight / 2;

            if (collectedKeys >= totalKeys && // 只有收集了所有钥匙才能通关
                playerX + playerWidth / 2 >= doorCenterX - 30 &&
                playerX + playerWidth / 2 <= doorCenterX + 30 &&
                playerY + playerHeight / 2 >= doorCenterY - 40 &&
                playerY + playerHeight / 2 <= doorCenterY + 40
            ) {
                clearInterval(gameLoop);
                gameRunning = false;
                showVictory();
            }
            
            // 检查是否碰到播放按钮
            if (playButton && !timeRunning) {
                // 获取播放按钮的世界坐标
                const btnWorldX = levels[currentLevel].playButton.x;
                const btnWorldY = levels[currentLevel].playButton.y;
                const btnWidth = 30;
                const btnHeight = 30;
                
                // 使用世界坐标进行碰撞检测
                if (playerX + playerWidth > btnWorldX &&
                    playerX < btnWorldX + btnWidth &&
                    playerY + playerHeight > btnWorldY &&
                    playerY < btnWorldY + btnHeight) {
                    
                    timeRunning = true;
                    playButton.remove();
                    playButton = null;
                }
            }
        }
        
function playTickSound() {
    if (!audioContext) return;

    const osc = audioContext.createOscillator();
    osc.type = 'square'; 
    osc.frequency.value = tickTock ? 880 : 440; // 高低音交替

    const gainNode = audioContext.createGain();
    gainNode.gain.setValueAtTime(1.5, audioContext.currentTime); // 初始音量
    osc.connect(gainNode);
    gainNode.connect(tickGain);

    osc.start();
    osc.stop(audioContext.currentTime + 0.1); // 滴答声

    tickTock = !tickTock; // 切换高低音
}
        /**
         * 显示通关效果
         */
        function showVictory() {
            victoryEffect.style.opacity = 1;
            victoryText.style.opacity = 1;
            victoryText.style.transform = 'translate(-50%, -50%) scale(1.2)';
            
            setTimeout(() => {
                victoryText.style.transform = 'translate(-50%, -50%) scale(1)';
            }, 500);
            
            setTimeout(() => {
                levelSelect.style.display = 'flex';
                victoryEffect.style.opacity = 0;
                victoryText.style.opacity = 0;
            }, 2000);
        }
        
        /**
         * 显示游戏失败效果
         */
        function showGameOver() {
            gameOverText.style.opacity = 1;
            gameOverText.style.transform = 'translate(-50%, -50%) scale(1.2)';
            
            setTimeout(() => {
                gameOverText.style.transform = 'translate(-50%, -50%) scale(1)';
            }, 500);
            
            setTimeout(() => {
                levelSelect.style.display = 'flex';
                gameOverText.style.opacity = 0;
            }, 2000);
        }
        
        /**
         * 更新时间显示位置
         */
        function updatePlayerTimePosition() {
            playerTime.style.left = (playerX - cameraX - 10) + 'px';
            playerTime.style.bottom = (playerY - cameraY + playerHeight + 5) + 'px';
        }
        
        /**
         * 更新时间显示内容
         */
        function updateTimer() {
            const displayTime = currentTime.toFixed(2);
            playerTime.textContent = displayTime;
            
            // 根据剩余时间改变颜色
            if (currentTime < 3) {
                playerTime.style.color = "#ff5555";
                playerTime.style.textShadow = "0 0 5px rgba(255, 0, 0, 0.7)";
            } else if (currentTime < 7) {
                playerTime.style.color = "#ffcc00";
                playerTime.style.textShadow = "0 0 5px rgba(255, 204, 0, 0.7)";
            } else {
                playerTime.style.color = "#ffffff";
                playerTime.style.textShadow = "1px 1px 3px rgba(0, 0, 0, 0.8)";
            }

        }
        
        // 键盘事件监听
        document.addEventListener('keydown', (e) => {
            if (e.key.toLowerCase() === 'a') keyStates.a = true;
            if (e.key.toLowerCase() === 'd') keyStates.d = true;
            if (e.key.toLowerCase() === 'k') {
                if (!keyStates.k) {
                    if (!isJumping) {
                        playerVelY = jumpForce;
                        isJumping = true;
                        canDoubleJump = true;
                    } else if (canDoubleJump) {
                        playerVelY = jumpForce * 0.8;
                        canDoubleJump = false;
                    }
                }
                keyStates.k = true;
            }
            if (e.key.toLowerCase() === 's') keyStates.s = true; 
            if (e.key === 'Escape') {
                if (gameRunning) {
                    initGame(currentLevel);
                }
            }
        });
        
        document.addEventListener('keyup', (e) => {
            if (e.key.toLowerCase() === 'a') keyStates.a = false;
            if (e.key.toLowerCase() === 'd') keyStates.d = false;
            if (e.key.toLowerCase() === 'k') keyStates.k = false;
            if (e.key.toLowerCase() === 's') keyStates.s = false;
        });
        
  
        function generateLevelButtons() {
            for (let i = 1; i <= 24; i++) {
                const btn = document.createElement('button');
                btn.className = 'level-btn';
                btn.dataset.level = i;
                btn.textContent = `第${i}关`;
                
                // 禁用未实现的关卡
                if (!levels[i]) {
                    btn.disabled = true;
                    btn.style.opacity = '0.5';
                }
                
                btn.addEventListener('click', () => {
                    const level = parseInt(btn.dataset.level);
                    if (levels[level]) {
                        currentLevel = level;
                        levelSelect.style.display = 'none';
                        initGame(level);
                    }
                });
                
                levelButtonsContainer.appendChild(btn);
            }
        }
        
        // 退出按钮事件
        exitBtn.addEventListener('click', () => {
            exitMenu.style.display = 'flex';
            if (gameLoop) clearInterval(gameLoop);
            gameRunning = false;
        });
        
        // 重新开始本关
        restartBtn.addEventListener('click', () => {
            exitMenu.style.display = 'none';
            initGame(currentLevel);
        });
        
        // 返回选关界面
        levelSelectBtn.addEventListener('click', () => {
            exitMenu.style.display = 'none';
            levelSelect.style.display = 'flex';
        });
        
        // 初始化游戏
        generateLevelButtons();
        levelSelect.style.display = 'flex';
    </script>
</body>
</html>